package com.chinamobile.iot.kafka;

import com.chinamobile.iot.config.KafkaConfiguration;
import com.chinamobile.iot.config.MqttConfiguration;
import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * Created by szl on 2017/7/14.
 */
@Component
public class KafkaProducerClient {

    @Autowired
    private MqttConfiguration mqttConfiguration;
    @Autowired
    private KafkaConfiguration kafkaConfiguration;

    private KafkaProducer<String, String> producer;

    public void close(){
        if (producer != null){
            producer.close();
        }
    }

    @PostConstruct
    public void init() {
        if (mqttConfiguration.isKafka()){
            producer = new KafkaProducer<>(kafkaConfiguration.producerProps());
        }
    }

    public void send(ProducerRecord<String, String> record){
        if (producer != null){
            producer.send(record);
        }
    }

    public void send(ProducerRecord<String, String> record, Callback callback){
        if (producer != null){
            producer.send(record, callback);
        }
    }
}
